<style lang="less" scoped>
@import "../assets/css/config.less";
.index {
  background: #f8f8f9;
}
.flex-row-center{
  display: flex;
  justify-content: center;
}
.loading {
  animation: myloading 1s linear infinite;
  margin-top: 100px;
}
@keyframes myloading {
  from {
    transform: rotate(0deg);
  }
  50% {
    transform: rotate(180deg);
  }
  to {
    transform: rotate(360deg);
  }
}
.list {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
}
.card {
  width: 80%;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
}
.submit_btn {
  width: 160px;
  margin: 20px auto;
  background-color: @color1;
  color: @white;
  font-size: 13px;
  box-shadow: none;
  border: none;
  &:hover{
    background-color: @color2;
    box-shadow: none;
  }
  &:active{
    background-color: @color3;
    box-shadow: none;
  }
}
.form {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
}
h4{
  margin: 15px;
  font-size:14px
}
.header{
  position: fixed;
  top:0;
  width: 100%;
  min-width: 1210px;
  z-index: 100;
}
</style>

<template>
  <div id="index">
    <div class="header">
      <myheader></myheader>
    </div>
    <Layout style="margin-top: 60px" id="content">
      <Layout :style="{padding: '0 24px 24px','background-color': 'white','min-width': '1210px'}">
        <div style="padding: 15px 6px">
          <my-breadcrumb :prop="breadcrumbList"></my-breadcrumb>
        </div>
        <div class="form" :label-width="80">
          <h4>题干</h4>
          <div ref="editor" style="text-align:left;width:90%;font-size:14px;z-index: 0;"></div>
          <div style="margin-top : 50px">
            <div style="width:100%">
              <h4>布鲁姆认知层次</h4>
              <Select v-model="bloom" style="width:200px">
                <Option :value="1">记忆</Option>
                <Option :value="2">理解</Option>
                <Option :value="3">应用</Option>
                <Option :value="4">分析</Option>
                <Option :value="5">综合</Option>
                <Option :value="6">评价和创造</Option>
              </Select>
            </div>
          </div>
          <div style="margin-top : 50px">
            <h4>题型</h4>
            <Select v-model="type" style="width:200px">
              <Option value="panduan" key="panduan">判断</Option>
              <Option value="xuanze" key="xuanze">选择</Option>
              <Option value="jianda" key="jianda">简答</Option>
            </Select>
          </div>

          <div v-if="type === 'xuanze'">
            <div class="form">
              <div @click="add_item">
                <Icon type="ios-add-circle-outline"/>
                <a>增加一个选项</a>
              </div>
              <div v-for="(item, key) in items" :key="key">
                {{key + 1}}
                <Input
                  style="width: 500px"
                  v-model="items[key]"
                  size="large"
                  placeholder="请输入一个新选项"
                />
                <Icon @click="delete_Item(key)" size="15" type="md-close-circle"/>
              </div>
            </div>
          </div>

          <div>
            <h4 v-if="type !== 'jianda'">答案</h4>
            <Select v-if="type === 'xuanze'" multiple v-model="answer" style="width:200px">
              <Option v-for="(item, key) in items" :key="key" :value="(key+1)+''">{{key+1}}</Option>
            </Select>
            <Select v-if="type === 'panduan'" v-model="answer" style="width:200px">
              <Option value="yes">对</Option>
              <Option value="no">错</Option>
            </Select>
          </div>

          <h4>答案解析</h4>
          <div ref="illustration" style="text-align:left;width:90%;font-size:14px;z-index: 0;"></div>

          <div>
            <Button
              v-if="$route.params.state === 'new'"
              class="submit_btn"
              @click="submit()"
            >新建</Button>
            <Button
              v-if="$route.params.state === 'edit'"
              class="submit_btn"
              @click="modify()"
            >提交修改</Button>
          </div>
        </div>
      </Layout>
    </Layout>
  </div>
</template>

<script>
import header from "../components/header.vue";
import myBreadcrumb from "../components/myBreadcrumb.vue";
import E from "wangeditor";
import {
  addQuestion,
  modifyQuestion
} from "../api/api";

export default {
  name: "give_question",
  data: function() {
    return {
      bg: {
        width: `${window.innerWidth}px`,
        height: "auto",
        overflow: "scroll"
      },
      editorContent: "",
      bloom: "",
      type: "",
      items: [],
      answer: [],
      illustrationContent: "",
      _id: "",
      breadcrumbList: []
    };
  },
  created(){
    // 获取面包屑数组
    if (JSON.parse(sessionStorage.getItem("pathList")) != null) {
      let breadcrumbList = JSON.parse(sessionStorage.getItem("pathList"));
      this.breadcrumbList = [...breadcrumbList, {name: '为知识点出题'}]
    }
  },
  mounted() {
    window.onresize = () => {
      return (() => {
        let content_top = document.getElementById("content").offsetTop;
        this.bg.height = `${window.innerHeight - content_top}px`;
        this.bg.width = `${window.innerWidth}px`;
      })();
    };
    let content_top = document.getElementById("content").offsetTop;
    this.bg.height = `${window.innerHeight - content_top}px`;

    this.$nextTick(() => {
      var editor = new E(this.$refs.editor);
      var illustration = new E(this.$refs.illustration);

      editor.customConfig.onchange = html => {
        this.editorContent = html;
      };

      illustration.customConfig.onchange = html => {
        this.illustrationContent = html;
      };

      var url = "";
      if (process.env.NODE_ENV === "development") {
        url = "http://localhost:8080/api/uploadImg";
      } else if (process.env.NODE_ENV === "production") {
        url = "https://www.ourspark.org/api/uploadImg";
      }
      editor.customConfig.uploadImgServer = url; // 上传图片到服务器
      illustration.customConfig.uploadImgServer = url; // 上传图片到服务器
      editor.create();
      illustration.customConfig.zIndex = 0;
      illustration.create();
      if (this.$route.params.question === undefined) {
        editor.txt.html("<p>请在此输入题干</p>");
        illustration.txt.html("<p>请在此输入题目解析</p>");
        this._id = this.$route.params._id
      } else {
        editor.txt.html(this.$route.params.question.question);
        this.editorContent = this.$route.params.question.question;
        this.bloom = this.$route.params.question.bloom;
        this.type = this.$route.params.question.type;
        this.items = this.$route.params.question.items;
        this.answer = this.$route.params.question.answer;
        this.illustrationContent = this.$route.params.question.illustrationContent;
        illustration.txt.html(this.$route.params.question.illustrationContent);
      }
    })
    
    // editor.customConfig.uploadImgHooks = {
    //   // before: function(xhr, editor, files) {
    //   //   // 图片上传之前触发
    //   //   // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，files 是选择的图片文件
    //   //   // 如果返回的结果是 {prevent: true, msg: 'xxxx'} 则表示用户放弃上传
    //   //   // return {
    //   //   //     prevent: true,
    //   //   //     msg: '放弃上传'
    //   //   // }
    //   // },
    //   success: function(xhr, editor, result) {
    //     // 图片上传并返回结果，图片插入成功之后触发
    //     // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，result 是服务器端返回的结果
    //   }
    //   // fail: function(xhr, editor, result) {
    //   //   // 图片上传并返回结果，但图片插入错误时触发
    //   //   // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，result 是服务器端返回的结果
    //   // },
    //   // error: function(xhr, editor) {
    //   //   // 图片上传出错时触发
    //   //   // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象
    //   // },
    //   // timeout: function(xhr, editor) {
    //   //   // 图片上传超时时触发
    //   //   // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象
    //   // },

    //   // // 如果服务器端返回的不是 {errno:0, data: [...]} 这种格式，可使用该配置
    //   // // （但是，服务器端返回的必须是一个 JSON 格式字符串！！！否则会报错）
    //   // customInsert: function(insertImg, result, editor) {
    //   //   // 图片上传并返回结果，自定义插入图片的事件（而不是编辑器自动插入图片！！！）
    //   //   // insertImg 是插入图片的函数，editor 是编辑器对象，result 是服务器端返回的结果

    //   //   // 举例：假如上传图片成功后，服务器端返回的是 {url:'....'} 这种格式，即可这样插入图片：
    //   //   // var url = result.url;
    //   //   // insertImg(url);

    //   //   // result 必须是一个 JSON 格式字符串！！！否则报错
    //   // }
    // };

    
  },
  components: {
    myheader: header,
    'my-breadcrumb': myBreadcrumb
  },
  methods: {
    add_item() {
      this.items.push("");
    },
    delete_Item(key) {
      this.items.splice(key, 1);
    },
    modify() {
      if (this.editorContent === "") {
        this.$Modal.confirm({
          title: "提示",
          content: "题干不能为空哦！"
        });
      } else if (this.bloom === "") {
        this.$Modal.confirm({
          title: "提示",
          content: "布鲁姆认知层次必须选！"
        });
      } else if (this.type === "") {
        this.$Modal.confirm({
          title: "提示",
          content: "题型必须选！"
        });
      } else if (this.type === "xuanze" && this.items.length == 0) {
        this.$Modal.confirm({
          title: "提示",
          content: "不能没有选项！"
        });
      } else if (this.type!=="jianda" && (this.answer === "" || this.answer.length === 0)) {
        this.$Modal.confirm({
          title: "提示",
          content: "必须提供该题答案！"
        });
      } else if (this.type!=="jianda" && this.illustrationContent === "") {
        this.$Modal.confirm({
          title: "提示",
          content: "必须提供该题答案解析！"
        });
      } else {
        modifyQuestion({
          _id: this.$route.params.question._id,
          question: this.editorContent,
          bloom: this.bloom,
          type: this.type,
          items: this.items,
          answer: this.answer,
          illustrationContent: this.illustrationContent
        })
          .then(response => {
            if (response.state === true) {
              this.$Message.success("修改成功");
              this.$router.go(-1);
            } else {
              this.$Message.error("修改失败！ " + response.msg);
            }
          })
          .catch(error => {
            this.$Message.error(error.status);
          });
      }
    },
    submit() {
      if (this.editorContent === "") {
        this.$Modal.confirm({
          title: "提示",
          content: "题干不能为空哦！"
        });
      } else if (this.bloom === "") {
        this.$Modal.confirm({
          title: "提示",
          content: "布鲁姆认知层次必须选！"
        });
      } else if (this.type === "") {
        this.$Modal.confirm({
          title: "提示",
          content: "题型必须选！"
        });
      } else if (this.type === "xuanze" && this.items.length == 0) {
        this.$Modal.confirm({
          title: "提示",
          content: "不能没有选项！"
        });
      } else if (this.type!=="jianda" && this.items.answer === "") {
        this.$Modal.confirm({
          title: "提示",
          content: "必须提供该题答案！"
        });
      } else if (this.type!=="jianda" && this.illustrationContent === "") {
        this.$Modal.confirm({
          title: "提示",
          content: "必须提供该题答案解析！"
        });
      } else {
        addQuestion({
          point_id: this._id,
          position: this.$route.params.position,
          seq: this.$route.params.seq,
          UUID: sessionStorage.UUID,
          question: this.editorContent,
          bloom: this.bloom,
          type: this.type,
          items: this.items,
          answer: this.answer,
          illustrationContent: this.illustrationContent
        })
          .then(response => {
            if (response.state === true) {
              this.$Message.success("提交成功");
              this.$router.go(-1);
            } else {
              this.$Message.error(response.msg);
            }
          })
          .catch(error => {
            this.$Message.error(error.status);
          });
      }
    }
  }
};
</script>